package eproject.mm.com.projectsupervision.fragment;


import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.suke.widget.SwitchButton;

import org.w3c.dom.Text;

import java.util.Timer;
import java.util.TimerTask;

import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.activity.DataListActivity;
import eproject.mm.com.projectsupervision.activity.MessageContentActivity;
import eproject.mm.com.projectsupervision.activity.PasswordActivity;
import eproject.mm.com.projectsupervision.activity.ServerSettingActivity;
import eproject.mm.com.projectsupervision.constant.Constant;
import eproject.mm.com.projectsupervision.service.DemoService;
import eproject.mm.com.projectsupervision.service.LocationService;
import eproject.mm.com.projectsupervision.service.StepService;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import eproject.mm.com.projectsupervision.util.StepCountCheckUtil;
import eproject.mm.com.projectsupervision.util.TimeUtil;

import static android.content.Context.SENSOR_SERVICE;

/**
 * A simple {@link Fragment} subclass.
 */
public class ProfileFragment extends Fragment implements android.os.Handler.Callback,View.OnClickListener,SensorEventListener {
    private static final String TAG = ProfileFragment.class.getName();

    //private SwitchButton sb_gps;//,sb_sensor;
    private TextView tv_stepCount,tv_localUploadTime;

    private LocationService locationService;

    private RelativeLayout re_myinfo,rl_myPlanReport,rl_myProblem,rl_myModify,rl_myCheck, rl_setting;
    private SensorManager sensorManager;
    MyLocalReceiver receiver;

    TextView tv_name,tv_orgname;

    public ProfileFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        //sb_gps = (SwitchButton)view.findViewById(R.id.sb_gps);
        //sb_sensor = (SwitchButton)view.findViewById(R.id.sb_sensor);
        // Inflate the layout for this fragment

        re_myinfo = (RelativeLayout)view.findViewById(R.id.re_myinfo);
        rl_myPlanReport = (RelativeLayout)view.findViewById(R.id.rl_myPlanReport);
        rl_myProblem = (RelativeLayout)view.findViewById(R.id.rl_myProblem);
        rl_myModify = (RelativeLayout)view.findViewById(R.id.rl_myModify);
        rl_myCheck = (RelativeLayout)view.findViewById(R.id.rl_myCheck);
        rl_setting = (RelativeLayout)view.findViewById(R.id.rl_setting);

        tv_stepCount = (TextView)view.findViewById(R.id.tv_stepCount);
        tv_localUploadTime = (TextView)view.findViewById(R.id.tv_localUploadTime);

        tv_name = (TextView)view.findViewById(R.id.tv_name);
        tv_orgname = (TextView)view.findViewById(R.id.tv_orgname);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        tv_name.setText(PrjApplication.getInstance().getUserName());
        tv_orgname.setText(PrjApplication.getInstance().getOrgName());

        //locationService = ((PrjApplication)getActivity().getApplication()).locationService;

//        sb_gps.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(SwitchButton buttonView, boolean isChecked) {
//                if(isChecked){
//                    Intent intent = new Intent(getContext(), DemoService.class);
//                    isBind = getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
//                    getActivity().startService(intent);
//                }else{
//                    if (isBind) {
//                        getActivity().unbindService(conn);
//                        isBind = false;
//                    }
//                }
////                if(isChecked){
////                    locationService.registerListener(mListener);
////                    locationService.setLocationOption(locationService.getDefaultLocationClientOption());
////                    locationService.start();// 定位SDK
////                }else{
////                    locationService.unregisterListener(mListener); //注销掉监听
////                    locationService.stop(); //停止定位服务
////                }
//            }
//        });

        sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE);

//        sb_sensor.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(SwitchButton buttonView, boolean isChecked) {
//                if(isChecked){
//                    Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
//                    if (countSensor != null) {
//                        sensorManager.registerListener(ProfileFragment.this, countSensor, SensorManager.SENSOR_DELAY_NORMAL);
//                    }
////                    if (StepCountCheckUtil.isSupportStepCountSensor(getContext())) {
////                        Intent intent = new Intent(getContext(), StepService.class);
////                        isBind = getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
////                        getActivity().startService(intent);
////                    }
//                }else{
////                    if (isBind) {
////                        getActivity().unbindService(conn);
////                        isBind = false;
////                    }
//                }
//            }
//        });

        re_myinfo.setOnClickListener(this);
        rl_myPlanReport.setOnClickListener(this);
        rl_myModify.setOnClickListener(this);
        rl_myProblem.setOnClickListener(this);
        rl_myCheck.setOnClickListener(this);
        rl_setting.setOnClickListener(this);

        tv_stepCount.setText(String.valueOf(PrjApplication.getInstance().getCurStepCount()));

        receiver = new MyLocalReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(PrjApplication.getInstance().LocalAction);
        filter.addAction(PrjApplication.getInstance().StepAction);
        getContext().registerReceiver(receiver, filter);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        int tempStep = (int) event.values[0];
        Toast.makeText(getActivity(),String.valueOf(tempStep),Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    public void onClick(View view){
        String type = "";
        switch (view.getId()){
            case R.id.rl_myPlanReport:
                type = "planreport";
                break;
            case R.id.rl_myProblem:
                type = "problem";
                break;
            case R.id.rl_myModify:
                type = "modify";
                break;
            case R.id.rl_myCheck:
                type = "check";
                break;
            case R.id.rl_setting:
                Intent intent = new Intent(getActivity(), ServerSettingActivity.class);
                startActivityForResult(intent,0);
                return;
            case R.id.re_myinfo:
                Intent intentPass = new Intent(getActivity(), PasswordActivity.class);
                startActivityForResult(intentPass,0);
                return;
        }
        if(!type.equals("")){
            Intent intent = new Intent(getActivity(), DataListActivity.class);
            Bundle bundle=new Bundle();
            bundle.putString("type", type);
            intent.putExtras(bundle);
            startActivityForResult(intent,0);
        }
    }
    String localString = "";
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {

//                String _str = location.getLongitude()+","+location.getLatitude();
//                if(!localString.equals(_str)){
//                    localString = _str;
//
//                    //上传
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            try {
//                                String projectStr = HttpUtil.get("/insertPos?pos="+localString);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }).start();
//                }
//                StringBuffer sb = new StringBuffer(256);
//                sb.append("time : ");
//                /**
//                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
//                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
//                 */
//                sb.append(location.getTime());
//                sb.append("\nlocType : ");// 定位类型
//                sb.append(location.getLocType());
//                sb.append("\nlocType description : ");// *****对应的定位类型说明*****
//                sb.append(location.getLocTypeDescription());
//                sb.append("\nlatitude : ");// 纬度
//                sb.append(location.getLatitude());
//                sb.append("\nlontitude : ");// 经度
//                sb.append(location.getLongitude());
//                sb.append("\nradius : ");// 半径
//                sb.append(location.getRadius());
//                sb.append("\nCountryCode : ");// 国家码
//                sb.append(location.getCountryCode());
//                sb.append("\nCountry : ");// 国家名称
//                sb.append(location.getCountry());
//                sb.append("\ncitycode : ");// 城市编码
//                sb.append(location.getCityCode());
//                sb.append("\ncity : ");// 城市
//                sb.append(location.getCity());
//                sb.append("\nDistrict : ");// 区
//                sb.append(location.getDistrict());
//                sb.append("\nStreet : ");// 街道
//                sb.append(location.getStreet());
//                sb.append("\naddr : ");// 地址信息
//                sb.append(location.getAddrStr());
//                sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
//                sb.append(location.getUserIndoorState());
//                sb.append("\nDirection(not all devices have value): ");
//                sb.append(location.getDirection());// 方向
//                sb.append("\nlocationdescribe: ");
//                sb.append(location.getLocationDescribe());// 位置语义化信息
//                sb.append("\nPoi: ");// POI信息
//                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
//                    for (int i = 0; i < location.getPoiList().size(); i++) {
//                        Poi poi = (Poi) location.getPoiList().get(i);
//                        sb.append(poi.getName() + ";");
//                    }
//                }
//                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
//                    sb.append("\nspeed : ");
//                    sb.append(location.getSpeed());// 速度 单位：km/h
//                    sb.append("\nsatellite : ");
//                    sb.append(location.getSatelliteNumber());// 卫星数目
//                    sb.append("\nheight : ");
//                    sb.append(location.getAltitude());// 海拔高度 单位：米
//                    sb.append("\ngps status : ");
//                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
//                    sb.append("\ndescribe : ");
//                    sb.append("gps定位成功");
//                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
//                    // 运营商信息
//                    if (location.hasAltitude()) {// *****如果有海拔高度*****
//                        sb.append("\nheight : ");
//                        sb.append(location.getAltitude());// 单位：米
//                    }
//                    sb.append("\noperationers : ");// 运营商信息
//                    sb.append(location.getOperators());
//                    sb.append("\ndescribe : ");
//                    sb.append("网络定位成功");
//                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//                    sb.append("\ndescribe : ");
//                    sb.append("离线定位成功，离线定位结果也是有效的");
//                } else if (location.getLocType() == BDLocation.TypeServerError) {
//                    sb.append("\ndescribe : ");sb.append("\ndescribe : ");
//                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
//                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                    sb.append("\ndescribe : ");
//                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
//                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                    sb.append("\ndescribe : ");
//                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
//                }
//
//                Log.d(TAG,sb.toString());
            }
        }

    };


    private boolean isBind = false;
    private Messenger mGetReplyMessenger = new Messenger(new Handler(this));
    private Messenger messenger;

    private TimerTask timerTask;
    private Timer timer;
    private ServiceConnection conn = new ServiceConnection() {
        /**
         * 在建立起于Service的连接时会调用该方法，目前Android是通过IBind机制实现与服务的连接。
         * @param name 实际所连接到的Service组件名称
         * @param service 服务的通信信道的IBind，可以通过Service访问对应服务
         */
        @Override
        public void onServiceConnected(ComponentName name, final IBinder service) {
            /**
             * 设置定时器，每个三秒钟去更新一次运动步数
             */
//            timerTask = new TimerTask() {
//                @Override
//                public void run() {
//                    try {
//                        messenger = new Messenger(service);
//                        Message msg = Message.obtain(null, Constant.MSG_FROM_CLIENT);
//                        msg.replyTo = mGetReplyMessenger;
//                        messenger.send(msg);
//                    } catch (RemoteException e) {
//                        e.printStackTrace();
//                    }
//                }
//            };
//            timer = new Timer();
//            timer.schedule(timerTask, 0, 3000);
        }

        /**
         * 当与Service之间的连接丢失的时候会调用该方法，
         * 这种情况经常发生在Service所在的进程崩溃或者被Kill的时候调用，
         * 此方法不会移除与Service的连接，当服务重新启动的时候仍然会调用 onServiceConnected()。
         * @param name 丢失连接的组件名称
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //这里用来获取到Service发来的数据
            case Constant.MSG_FROM_SERVER:

                break;
        }
        return false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getContext().unregisterReceiver(receiver);
//        if (isBind) {
//            getActivity().unbindService(conn);
//            isBind = false;
//        }
    }

    public class MyLocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if(action.equals(PrjApplication.getInstance().LocalAction)){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv_localUploadTime.setText(TimeUtil.getCurTime());
                    }
                });
            }else if(action.equals(PrjApplication.getInstance().StepAction)){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Bundle bundle = intent.getExtras();
                        int step = bundle.getInt("step");
                        tv_stepCount.setText(String.valueOf(step));
                    }
                });
            }
        }
    }
}
